// composables/useWebSocket.js
import {ref, reactive, onUnmounted} from 'vue';

export function useSocket(options = {}) {
    // 状态
    const isConnected = ref(false);
    const reconnectCount = ref(0);
    const messages = ref([]);
    const socketTask = ref(null);

    // 配置
    const config = reactive({
        url: options.url || '',
        maxReconnectCount: options.maxReconnectCount || 5, // 最大重连次数
        reconnectInterval: options.reconnectInterval || 3000, // 重连间隔
        autoConnect: options.autoConnect !== false, // 自动连接
        heartBeatInterval: options.heartBeatInterval || 5000, // 心跳间隔
        ...options,
    });

    // 心跳计时器
    let heartBeatTimer = null;

    // 连接 WebSocket
    const connect = () => {
        if (socketTask.value) {
            disconnect();
        }

        // console.log('正在连接 WebSocket...');
        socketTask.value = uni.connectSocket({
            url: config.url,
            header: {
                'content-type': 'application/json',
            },
            success: () => {
                console.log('[WebSocket] 连接创建成功');
            },
            fail: (err) => {
                console.error('[WebSocket] 连接创建失败', err);
                options.onError?.(err);
                handleReconnect();
            },
        });

        bindEvents();
    };

    // 绑定事件
    const bindEvents = () => {
        if (!socketTask.value) return;

        socketTask.value.onOpen(() => {
            console.log('[WebSocket] 连接已打开');
            isConnected.value = true;
            reconnectCount.value = 0;
            options.onOpen?.();
            startHeartBeat();
        });

        socketTask.value.onMessage((res) => {
            const message = parseMessage(res.data);
            options.onMessage?.(message);
            messages.value.push(message);
        });

        socketTask.value.onError((err) => {
            console.error('[WebSocket] 连接错误:', err);
            isConnected.value = false;
            options.onError?.(err);
            handleReconnect();
        });

        socketTask.value.onClose((res) => {
            console.log('[WebSocket] 连接已关闭', res);
            isConnected.value = false;
            options.onClose?.(res);
            stopHeartBeat();
        });
    };

    // 发送消息
    const send = (data) => {
        if (!isConnected.value || !socketTask.value) {
            throw new Error('WebSocket 未连接');
        }

        const message = typeof data === 'string' ? data : JSON.stringify(data);

        return new Promise((resolve, reject) => {
            socketTask.value.send({
                data: message,
                success: () => {
                    console.log('消息发送成功');
                    resolve();
                },
                fail: (err) => {
                    console.error('消息发送失败', err);
                    reject(err);
                },
            });
        });
    };

    // 断开连接
    const disconnect = () => {
        if (socketTask.value && socketTask.value.readyState === 1) {
            socketTask.value.close();
            socketTask.value = null;
        }
        isConnected.value = false;
        stopHeartBeat();
    };

    // 重连机制
    const handleReconnect = () => {
        if (reconnectCount.value >= config.maxReconnectCount) {
            console.log('[WebSocket] 已达到最大重连次数');
            options.onMaxReconnect?.();
            return;
        }

        reconnectCount.value++;
        console.log(`[WebSocket] 尝试第 ${reconnectCount.value} 次重连...`);

        setTimeout(() => {
            connect();
        }, config.reconnectInterval);
    };

    // 解析消息
    const parseMessage = (data) => {
        try {
            return JSON.parse(data);
        } catch {
            return {
                type: 'text',
                content: data,
                timestamp: Date.now(),
            };
        }
    };

    // 心跳检测
    const startHeartBeat = () => {
        if (!config.heartBeatInterval) return;

        stopHeartBeat();

        heartBeatTimer = setInterval(() => {
            if (isConnected.value) {
                send({
                    type: 'ping',
                    timestamp: Date.now(),
                }).catch((err) => {
                    console.error('[WebSocket] 心跳发送失败', err);
                });
            }
        }, config.heartBeatInterval);
    };

    const stopHeartBeat = () => {
        if (heartBeatTimer) {
            clearInterval(heartBeatTimer);
            heartBeatTimer = null;
        }
    };

    // 清空消息
    const clearMessages = () => {
        messages.value = [];
    };

    // 自动连接
    if (config.autoConnect && config.url) {
        connect();
    }

    // 组件卸载时清理
    onUnmounted(() => {
        disconnect();
    });

    return {
        // 状态
        isConnected,
        reconnectCount,
        messages,

        // 方法
        connect,
        disconnect,
        send,
        clearMessages,
    };
}
